//
//  UIView+Extension.swift
//  BTE
//
//  Created by Mike Zhang on 2025/8/14.
//

import UIKit

extension UIView {
    
    // MARK: - 初始化优化
    /// 创建一个带有背景色的视图
    convenience init(backgroundColor: UIColor) {
        self.init(frame: .zero)
        self.backgroundColor = backgroundColor
    }
    
    /// 创建一个带有背景色和圆角的视图
    convenience init(backgroundColor: UIColor, cornerRadius: CGFloat) {
        self.init(frame: .zero)
        self.backgroundColor = backgroundColor
        self.layer.cornerRadius = cornerRadius
        self.clipsToBounds = true
    }
    
    // MARK: - 圆角处理
    /// 设置特定角的圆角
    /// - Parameters:
    ///   - corners: 需要圆角的角
    ///   - radius: 圆角半径
    func roundCorners(_ corners: UIRectCorner, radius: CGFloat) {
        clipsToBounds = true
        
        if #available(iOS 11.0, *) {
            // 使用高性能方式 (iOS 11+)
            var cornerMask = CACornerMask()
            if corners.contains(.topLeft) { cornerMask.insert(.layerMinXMinYCorner) }
            if corners.contains(.topRight) { cornerMask.insert(.layerMaxXMinYCorner) }
            if corners.contains(.bottomLeft) { cornerMask.insert(.layerMinXMaxYCorner) }
            if corners.contains(.bottomRight) { cornerMask.insert(.layerMaxXMaxYCorner) }
            if corners.contains(.allCorners) { cornerMask = [.layerMinXMinYCorner, .layerMaxXMinYCorner, .layerMinXMaxYCorner, .layerMaxXMaxYCorner] }
            
            layer.cornerRadius = radius
            layer.maskedCorners = cornerMask
        } else {
            // 兼容旧版本的回退方案
            let path = UIBezierPath(
                roundedRect: bounds,
                byRoundingCorners: corners,
                cornerRadii: CGSize(width: radius, height: radius))
                
                let mask = CAShapeLayer()
                mask.path = path.cgPath
                layer.mask = mask
        }
    }
    
    // MARK: - 渐变处理
    
    /// 应用渐变背景
    /// - Parameters:
    ///   - colors: 渐变颜色数组
    ///   - startPoint: 渐变起点 (0,0) 到 (1,1)
    ///   - endPoint: 渐变终点 (0,0) 到 (1,1)
    func applyGradientBackground(colors: [UIColor],
                                 startPoint: CGPoint = CGPoint(x: 0.5, y: 0.0),
                                 endPoint: CGPoint = CGPoint(x: 0.5, y: 1.0)) {
        // 创建或更新渐变层
        let gradientLayer: CAGradientLayer
        if let existingLayer = layer.sublayers?.first(where: { $0.name == GradientLayerName }) as? CAGradientLayer {
            gradientLayer = existingLayer
        } else {
            gradientLayer = CAGradientLayer()
            gradientLayer.name = GradientLayerName
            layer.insertSublayer(gradientLayer, at: 0)
        }
        
        // 配置渐变
        gradientLayer.colors = colors.map { $0.cgColor }
        gradientLayer.startPoint = startPoint
        gradientLayer.endPoint = endPoint
        gradientLayer.frame = bounds
    }
    
    /// 更新渐变层大小（应在布局变化后调用）
    func updateGradientFrame() {
        guard let gradientLayer = layer.sublayers?.first(where: { $0.name == GradientLayerName }) as? CAGradientLayer else {
            return
        }
        
        CATransaction.begin()
        CATransaction.setDisableActions(true) // 禁止动画
        gradientLayer.frame = bounds
        CATransaction.commit()
    }
    
    /// 移除渐变背景
    func removeGradientBackground() {
        layer.sublayers?.removeAll { $0.name == GradientLayerName }
    }
    
    // MARK: - 阴影处理
    
    /// 添加阴影效果
    /// - Parameters:
    ///   - color: 阴影颜色
    ///   - opacity: 阴影不透明度 (0-1)
    ///   - offset: 阴影偏移
    ///   - radius: 阴影模糊半径
    func addShadow(color: UIColor = .black,
                   opacity: Float = 0.2,
                   offset: CGSize = CGSize(width: 0, height: 2),
                   radius: CGFloat = 4.0) {
        layer.shadowColor = color.cgColor
        layer.shadowOpacity = opacity
        layer.shadowOffset = offset
        layer.shadowRadius = radius
        layer.masksToBounds = false
    }
    
    /// 移除所有阴影效果
    func removeShadow() {
        layer.shadowColor = nil
        layer.shadowOpacity = 0
        layer.shadowOffset = .zero
        layer.shadowRadius = 0
    }
    
    // MARK: - 边框处理
    
    /// 添加边框
    /// - Parameters:
    ///   - color: 边框颜色
    ///   - width: 边框宽度
    func addBorder(color: UIColor, width: CGFloat = 1.0) {
        layer.borderColor = color.cgColor
        layer.borderWidth = width
    }
    
    /// 移除边框
    func removeBorder() {
        layer.borderColor = nil
        layer.borderWidth = 0
    }
    
    // MARK: - 私有常量
    private struct AssociatedKeys {
        static var GradientLayerName = "GradientBackgroundLayer"
    }
    
    private var GradientLayerName: String {
        return AssociatedKeys.GradientLayerName
    }
}
